package worker

import (
	"cron-go/internal/pkg/crontab/dao"
	"cron-go/internal/pkg/crontab/enum"
	"cron-go/internal/pkg/crontab/models"
	"cron-go/internal/pkg/utils/notify/dingtalk"
	"cron-go/internal/pkg/utils/notify/feishu"
	"cron-go/internal/pkg/utils/notify/webhook"
	"fmt"

	"github.com/go-liam/util/conv"
)

// 通知工人
type NotifyModel struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

type NotifyWebHookModel struct {
	Url   string      `json:"type"`
	Token string      `json:"tokens"`
	Body  interface{} `json:"body"`
}

type NotifyFeiShuModel struct {
	WebHookUrl string `json:"webHookUrl"`
	Title      string `json:"title"`
	Text       string `json:"text"`
	Link       string `json:"link"`
	IsAtAll    bool   `json:"isAtAll"`
	IsSuccess  int    `json:"isSuccess"` // 1 成功要通知
}

type NotifyDingTalkModel struct {
	RobotToken  string `json:"robotToken"`
	RobotSecret string `json:"robotSecret"`
	Title       string `json:"title"`
	Text        string `json:"text"`
	Link        string `json:"link"`
	IsAtAll     bool   `json:"isAtAll"`
}

func NotifyWorkByID(taskID int64, workerStatus int) bool {
	m, _ := dao.TaskDaoServer.FindOneByID(taskID)
	return NotifyWork(m, workerStatus)
}

func NotifyWork(m *models.TaskMysqlModel, workerStatus int) bool {
	if m.IsNotify != 1 {
		return false
	}
	conf := m.NotifyConfig
	if len(conf) < 10 {
		return false
	}
	nMs := make([]NotifyModel, 0)
	conv.JsonStringToStruct(conf, &nMs)
	//json.Unmarshal(conf, nMs)
	for _, i := range nMs {
		fmt.Printf("[INFO]Notify Type: %+v\n", i.Type)
		ty := i.Type
		switch ty {
		case "webhook":
			NotifyWebHookWork(m, i.Data, workerStatus)
		case "feishu":
			NotifyFeiShuWork(m, i.Data, workerStatus)
		case "dingtalk":
			NotifyDingTalkWork(m, i.Data, workerStatus)
		default:
			return false
		}
	}
	// println(conf)
	FinishNotifyWorker(m, 1)
	return true
}

func NotifyWebHookWork(m *models.TaskMysqlModel, cof interface{}, workerStatus int) bool {
	if cof == nil {
		return false
	}
	w := cof.(map[string]interface{})
	wM := new(NotifyWebHookModel)
	if workerStatus == enum.DoStatusSuccess {
		if conv.InterfaceToInt(w["isSuccess"], 0) == 0 {
			println("[INFO]Success no notify")
			return false //成功不用提示
		}
	}
	wM.Body = w["body"]
	wM.Url = conv.InterfaceToString(w["url"])
	wM.Token = conv.InterfaceToString(w["token"])
	if len(wM.Url) <= 10 {
		return false
	}
	sv := webhook.New(wM.Url, wM.Token)
	body := conv.StructToJsonString(wM.Body)
	r := sv.PostJson(body)
	fmt.Printf("r:%+v\n", r.StatusCode)
	return true
}

func NotifyFeiShuWork(m *models.TaskMysqlModel, cof interface{}, workerStatus int) bool {
	if cof == nil {
		return false
	}
	isAtAll := false
	w := cof.(map[string]interface{})
	wM := new(NotifyFeiShuModel)
	if workerStatus == enum.DoStatusFail {
		isAtAll = true
	}
	if workerStatus == enum.DoStatusSuccess {
		if conv.InterfaceToInt(w["isSuccess"], 0) == 0 {
			println("[INFO]Success no notify")
			return false //成功不用提示
		}
	}
	wM.WebHookUrl = conv.InterfaceToString(w["webHookUrl"])
	wM.Title = TitleLast(workerStatus) + m.Name
	wM.Text = fmt.Sprintf("[%v]%v", conv.Int64ToString(m.ID), w["text"])
	wM.Link = conv.InterfaceToString(w["link"])
	wM.IsAtAll = isAtAll //conv.InterfaceToBool(w["isAtAll"], false)
	return feishu.SendTextAndUrl(wM.WebHookUrl, wM.Title, wM.Text, wM.Link, wM.IsAtAll)
}

func NotifyDingTalkWork(m *models.TaskMysqlModel, cof interface{}, workerStatus int) bool {
	if cof == nil {
		return false
	}
	isAtAll := false
	if workerStatus == enum.DoStatusFail {
		isAtAll = true
	}
	w := cof.(map[string]interface{})
	wM := new(NotifyDingTalkModel)
	if workerStatus == enum.DoStatusSuccess {
		if conv.InterfaceToInt(w["isSuccess"], 0) == 0 {
			println("[INFO]Success no notify")
			return false //成功不用提示
		}
	}
	wM.RobotToken = conv.InterfaceToString(w["robotToken"])
	wM.RobotSecret = conv.InterfaceToString(w["robotSecret"])
	wM.Title = TitleLast(workerStatus) + m.Name
	wM.Text = fmt.Sprintf("[%v]%v", conv.Int64ToString(m.ID), w["text"])
	wM.Link = conv.InterfaceToString(w["link"])
	wM.IsAtAll = isAtAll
	return dingtalk.Send(wM.RobotToken, wM.RobotSecret, wM.Title, wM.Text, wM.Link, wM.IsAtAll)
}

func FinishNotifyWorker(t *models.TaskMysqlModel, status int) {
	//update task NotifyStatus
	dao.TaskDaoServer.UpdateNotifyStatus([]int64{t.ID}, status)
	//log
}

func TitleLast(status int) string {
	switch status {
	case 0:
		return ""
	case enum.DoStatusSuccess:
		return "[OK]"
	case enum.DoStatusFail:
		return "[Fail]"
	}
	return ""
}
